package com.ruoyi.web.controller.post;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.ruoyi.User.domain.User;
import com.ruoyi.User.service.IUserService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QiniuCloudUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.postComplain.domain.PostComplain;
import com.ruoyi.postComplain.service.IPostComplainService;
import com.ruoyi.system.util.StringUtil;
import com.ruoyi.topic.domain.Topic;
import com.ruoyi.topic.service.ITopicService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.post.domain.Post;
import com.ruoyi.post.service.IPostService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 帖子 信息操作处理
 *
 * @author ruoyi
 * @date 2019-10-12
 */
@Controller
@RequestMapping("/post/post")
public class PostController extends BaseController
{
    private String prefix = "post/post";

	private String prefix2 = "postComplain/postComplain";

	@Autowired
	private IPostService postService;

	@Autowired
	private IUserService userService;

	@Autowired
	private ITopicService topicService;

	@Autowired
	private IPostComplainService postComplainService;

	@RequiresPermissions("post:post:view")
	@GetMapping()
	public String post(ModelMap mmap)
	{
		Topic topic = new Topic();
		List<Topic> topicList = topicService.selectTopicList(topic);
		mmap.put("topicList", topicList);
		return prefix + "/post";
	}

	/**
	 * 查询帖子列表
	 */
	@RequiresPermissions("post:post:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Post post)
	{
		startPage();
        List<Post> list = postService.selectPostList(post);
		return getDataTable(list);
	}

	/**
	 * 查询待审核帖子列表
	 */
	@RequiresPermissions("post:post:list")
	@PostMapping("/verifyList")
	@ResponseBody
	public TableDataInfo verifyList(Post post)
	{
		startPage();
		post.setVerifyState("0");
		List<Post> list = postService.selectPostList(post);
		return getDataTable(list);
	}


	/**
	 * 导出帖子列表
	 */
	@RequiresPermissions("post:post:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Post post)
    {
    	List<Post> list = postService.selectPostList(post);
        ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
        return util.exportExcel(list, "post");
    }

	/**
	 * 新增帖子
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
		Topic topic = new Topic();
		List<Topic> topicList = topicService.selectTopicList(topic);
		mmap.put("topicList", topicList);
	    return prefix + "/add";
	}

	/**
	 * 新增保存帖子
	 */
	@RequiresPermissions("post:post:add")
	@Log(title = "帖子", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Post post)
	{
		String[] img = post.getPostImg().split(",");
		List<String> urlList=new ArrayList<String>();
		for (int i = 1 ; i < img.length; i=i+2) {
			String imgIndex = img[i];
			String urlIndex = imageToUrl(imgIndex);
			if("error".equals(urlIndex)){
				return AjaxResult.error("操作错误");
			} else {
				urlList.add(urlIndex);
			}
		}
		if(urlList.size()>0&&urlList!=null){
			String url = StringUtils.join(urlList,",");
			post.setPostImg(url);
		}
		post.setCreateDate(DateUtils.getNowDate());
		post.setValid(1);
		post.setUserId(0);
		post.setVerifyState("1");
		post.setLikeNum(0);
		post.setGlanceNum(0);
		post.setCommentsNum(0);
		post.setPostLevel(1);
		post.setIsComplain(2);
		return toAjax(postService.insertPost(post));
	}

	/**
	 * 修改帖子
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
		Post post = postService.selectPostById(id);
		Integer userId = post.getUserId();
		User user = userService.selectUserById(userId);
		String nickName = "";
		String topicName = "";
		if (user != null) {
			nickName = user.getNickname();
		} else if (userId == 0) {
			nickName = "校园帮帮";
		}
		Integer topicId = post.getTopicId();
		Topic topic = topicService.selectTopicById(topicId);
		if (topic != null) {
			topicName = topic.getTopicName();
		}
		mmap.put("nickName", nickName);
		mmap.put("topicName", topicName);
		mmap.put("post", post);
		return prefix + "/edit";
	}

	/**
	 * 修改保存帖子
	 */
	@RequiresPermissions("post:post:edit")
	@Log(title = "帖子", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Post post)
	{
		post.setModifyDate(DateUtils.getNowDate());
		return toAjax(postService.updatePost(post));
	}

	/**
	 * 删除帖子
	 */
	@RequiresPermissions("post:post:remove")
	@Log(title = "帖子", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
		String[] id = ids.split(",");
		for (String index : id) {
			Post persist = postService.selectPostById(Integer.parseInt(index));
			if(!StringUtils.isEmpty(persist.getPostImg())) {
				String[] url = persist.getPostImg().split(",");
				for (String example : url) {
					try {
						qiniuUtil.delete(example);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return toAjax(postService.deletePostByIds(ids));
	}

	/**
	 * 获取回复
	 */
	@GetMapping("/getResponse/{id}")
	public String getSign(@PathVariable("id") Integer id, ModelMap mmap)
	{
		mmap.put("postId", id);
		return prefix + "/postResponse";
	}

	@GetMapping("/getComplain/{id}")
	public String getComplain(@PathVariable("id") Integer id, ModelMap mmap)
	{
		mmap.put("postId", id);
		return prefix2 + "/postComplain";
	}

	@PostMapping("/ignoreVerify")
	@ResponseBody
	public AjaxResult ignoreVerify(Integer id) throws Exception {
//		PostComplain postComplain = postComplainService.selectPostComplainById(id);
//		postComplain.setComplainVerify("1");
//		postComplainService.updatePostComplain(postComplain);
//		Integer postId = postComplain.getPostId();
//		Post postPersist = postService.selectPostById(postId);
//		postPersist.setIsComplain(2);
//		return toAjax(postService.updatePost(postPersist));
		Post postPersist = postService.selectPostById(id);
		postPersist.setIsComplain(2);
		postPersist.setVerifyState("1");
		postService.updatePost(postPersist);
		return toAjax(postComplainService.updateComplainVerify(1,id));
		//return AjaxResult.error();

	}

	@PostMapping("/hideVerify")
	@ResponseBody
	public AjaxResult hideVerify(Integer id) throws Exception {
//		PostComplain postComplain = postComplainService.selectPostComplainById(id);
//		postComplain.setComplainVerify("2");
//		postComplainService.updatePostComplain(postComplain);
//		Integer postId = postComplain.getPostId();
//		Post postPersist = postService.selectPostById(postId);
//		postPersist.setIsComplain(2);
//		postPersist.setVerifyState("2");
//		return toAjax(postService.updatePost(postPersist));
		Post postPersist = postService.selectPostById(id);
		postPersist.setIsComplain(2);
		postPersist.setVerifyState("2");
		postService.updatePost(postPersist);
		return toAjax(postComplainService.updateComplainVerify(2,id));
	}




	public static String imageToUrl(String imgData) {
		if ((!StringUtils.isEmpty(imgData)) && (!imgData.startsWith("http"))) {
			imgData = imgData.substring(imgData.indexOf(",") + 1);
			byte[] bytes = Base64Utils.decodeFromString(imgData);
			String imageName = UUID.randomUUID().toString();
			QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
			try {
				String url = qiniuUtil.put64image(bytes, imageName);
				return url;
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		} else {
			return "error";
		}
	}

	@PostMapping("/ding")
	@ResponseBody
	public AjaxResult ding(Integer id) throws Exception {
//		PostComplain postComplain = postComplainService.selectPostComplainById(id);
//		postComplain.setComplainVerify("1");
//		postComplainService.updatePostComplain(postComplain);
//		Integer postId = postComplain.getPostId();
//		Post postPersist = postService.selectPostById(postId);
//		postPersist.setIsComplain(2);
//		return toAjax(postService.updatePost(postPersist));
		Post postPersist = postService.selectPostById(id);
		if(postPersist!=null){
			Integer level = postPersist.getPostLevel();
			if(level!=null&&level==2){
				return AjaxResult.error("该动态已是推荐动态，请勿重复推荐！");
			} else {
				postPersist.setPostLevel(2);
				postPersist.setRecommendDate(DateUtils.getNowDate());
				return toAjax(postService.updatePost(postPersist));
			}
		} else {
			return AjaxResult.error("该动态不存在！");
		}

		//return AjaxResult.error();

	}

}
